Respect Coder depth#904
Conversation
a56c226 to
ed20d79
Compare
|
This needs rebasing now. That said, it never occurred to me that |
|
Testing old versions, seems like this never really worked? gem "json", "2.2.0"
require 'json'
puts "JSON::VERSION: #{JSON::VERSION}"
puts JSON.generate({ foo: 1 }, object_nl: "\n", array_nl: "\n", space: " ", indent: " ", depth: 4) |
Coder currently ignores its depth and always resets it to 0 when generating a new JSON document.
ed20d79 to
0a4f320
Compare
I'm not sure what you mean, your example shows that |
Look at the opening braces. It's not respecting the depth. But the rest yes. |
|
The opening brace being on the first character is expected, because the enclosing code should be already indenting that part. For example, to go from a fragment with depth 1 to an Array: puts "[\n #{JSON.generate({ foo: 1 }, object_nl: "\n", array_nl: "\n", space: " ", indent: " ", depth: 1)}\n]"[
{
"foo": 1
}
] |
|
Ah right, that makes sense. |
|
Another example, using the generator to do the Array part instead of String interpolation: gem "json", ARGV.first
require 'json'
puts "JSON::VERSION: #{JSON::VERSION}"
cache_miss = 0
cache = Hash.new do |h, k|
cache_miss += 1
h[k] = Fragment.new(JSON.pretty_generate({ foo: k }, depth: 1))
end
class Fragment
def initialize(fragment)
@fragment = fragment
end
def to_json(*)
@fragment
end
end
puts JSON.pretty_generate((1..3).map(&cache))
puts "miss:#{cache_miss}"
cache_miss = 0
puts JSON.pretty_generate((1..3).map(&cache))
puts "miss:#{cache_miss}"This works all the way to ruby 2.7 for example: $ cat test.rb | container run --rm -i ruby:2.7 ruby
JSON::VERSION: 2.3.0
[
{
"foo": 1
},
{
"foo": 2
},
{
"foo": 3
}
]
miss:3
[
{
"foo": 1
},
{
"foo": 2
},
{
"foo": 3
}
]
miss:0 |
Builds on #903.
While working on #903, I realized
JSON::Coderwasn't respecting the depth it's given:This is not ideal, for example a user could want to emit pretty generated JSON, using Russian-doll caching and
JSON::Fragment(or a custom solution). To me it's a bug, so I just fixed it, now thatgenerate_json_datahas its owndepthit's pretty straightforward: etiennebarrie/json@move-depth-to-generate_json_data...etiennebarrie:json:respect-coder-depth